import re

from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from apps.users.models import User

# from django.contrib.auth.backends import ModelBackend
from meiduo_mall import settings


def get_user_by_username(username):
    try:
        if re.match(r'1[3-9]\d{9}', username):
            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None

    return user


# class UsernameMobileModelBackend(ModelBackend):
#     def authenticate(self, request, username=None, password=None, **kwargs):
#         user = get_user_by_username(username)
#         if user is not None and user.check_password(password):
#             return user



class UsernameMobileModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 通过用户名或者是手机号 来实现登陆
        # username 有可能是 手机号 也有可能是用户名
        # 我们通过正则来 区分手机号和用户名
        # try:
        #     if re.match(r'1[3-9]\d{9}',username):
        #
        #         user = User.objects.get(mobile=username)
        #     else:
        #
        #         user = User.objects.get(username=username)
        # except User.DoesNotExist:
        #     user = None
        user = get_user_by_username(username)

        if user is not None and user.check_password(password):
            return user


def generic_verify_url(user_id):
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)

    token = s.dumps({'user_id': user_id})

    return 'http://www.meiduo.site:8000/email_active/?token=%s' % token.decode()


def check_verify_token(token):
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
    try:
        result = s.loads(token)
    except Exception as e:
        return None
    else:
        user_id = result.get('user_id')
        return user_id
